/**
 *  函数防抖
 * @param func 要延迟执行的函数
 * @param delay 延迟时间（毫秒）
 * @returns 延迟执行的函数
 */
export function debounce(fn, dealy) {
  let timer = null
  return function () {
    let _this = this
    let _arguments = arguments
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(_this, _arguments)
    }, dealy)
  }
}
/**
 * 节流函数
 *
 * @param {Function} func - 需要进行节流处理的函数
 * @param {number} delay - 节流间隔时间（单位：毫秒）
 * @returns {Function} 节流处理后的函数
 */
export function throttle(func, delay) {
  let timeoutId
  let lastExec = 0

  function wrapper(...args) {
    const now = Date.now()

    function exec() {
      func.apply(this, args)
      lastExec = now
    }

    if (!timeoutId) {
      exec()
    } else {
      clearTimeout(timeoutId)
    }

    timeoutId = setTimeout(exec, Math.max(0, delay - (now - lastExec)))
  }

  return wrapper
}

/**
 * 判断对象的类型
 */
export const getObjType = obj => {
  var toString = Object.prototype.toString
  var map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  }
  if (obj instanceof Element) {
    return 'element'
  }
  return map[toString.call(obj)]
}
/**
 * 对象深度拷贝
 */
export const deepClone = data => {
  var type = getObjType(data)
  var obj
  if (type === 'array') {
    obj = []
  } else if (type === 'object') {
    obj = {}
  } else {
    // 不再具有下一层次
    return data
  }
  if (type === 'array') {
    for (var i = 0, len = data.length; i < len; i++) {
      obj.push(deepClone(data[i]))
    }
  } else if (type === 'object') {
    for (var key in data) {
      obj[key] = deepClone(data[key])
    }
  }
  return obj
}
/**
 * 列表滚动封装
 */
export const scrollAuto = (el, val) => {
  let scrollTimer = null

  const autoScroll = () => {
    const { scrollTop, scrollLeft, scrollWidth, scrollHeight, clientHeight } = el
    // 判断是否有滚动条
    if (scrollHeight <= clientHeight) return
    // 当有滚动条时，判断是否滚到到底部
    if (scrollTop + clientHeight >= scrollHeight) {
      el.scrollTop = 0
    } else {
      el.scrollTop += 1
    }
  }

  const toggleScrolling = event => {
    if (event.type === 'mouseenter') {
      if (scrollTimer) {
        clearInterval(scrollTimer)
        scrollTimer = null
      }
    } else if (event.type === 'mouseleave') {
      scrollTimer = setInterval(autoScroll, val)
    }
  }

  // 启动滚动
  scrollTimer = setInterval(autoScroll, val)

  // 添加事件监听器
  el.addEventListener('mouseenter', toggleScrolling)
  el.addEventListener('mouseleave', toggleScrolling)
}
